package homework1;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/Login2Servlet")
public class Login2Servlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		String name = request.getParameter("name1");
		String pwd = request.getParameter("pwd1");
		System.out.println(name+" "+pwd);
		String[] values = request.getParameterValues("zi");
		if (LoginTest.Login(name, pwd)) {
			if (values != null) {
				Cookie cookie1 = new Cookie("name", name);
				Cookie cookie2 = new Cookie("pwd", pwd);
				response.addCookie(cookie1);
				response.addCookie(cookie2);
			} else {
				Cookie cookie1 = new Cookie("name", null);
				Cookie cookie2 = new Cookie("pwd", null);
				cookie1.setMaxAge(0);
				cookie2.setMaxAge(0);
				response.addCookie(cookie1);
				response.addCookie(cookie2);
			}
			//request.getRequestDispatcher("index.html").forward(request, response);
			response.sendRedirect("index.html");
		} else if (name == null && pwd == null) {
			Cookie[] cookies = request.getCookies();
			if (cookies != null) {
				for (Cookie cookie : cookies) {
					if (cookie.getName().equals("name")) {
						System.out.println(cookie.getValue());
						name = cookie.getValue();
					}
					if (cookie.getName().equals("pwd")) {
						pwd = cookie.getValue();
						System.out.println(cookie.getValue());
					}
				}
			}

			if (LoginTest.Login(name, pwd)) {
				//request.getRequestDispatcher("index.html").forward(request, response);
				response.sendRedirect("index.html");
				return;
			} else {
				response.sendRedirect("login2.html");
				//request.getRequestDispatcher("login2.html").forward(request, response);
				return;
			}
		}else {
			response.sendRedirect("login2.html");
			//request.getRequestDispatcher("login2.html").forward(request, response);
			return;
		}
			
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
